package com.aaa.marketresearch.webclient.web;

import com.aaa.marketresearch.dataresource.domain.*;
import com.aaa.marketresearch.dataresource.service.*;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;

/**
 * @author Nail
 */
@Controller
public class DataNetService {

    @Autowired
    FamilyService familyService;

    @Autowired
    FamilyMemberService familyMemberService;

    @Autowired
    GoodsService goodsService;

    @Autowired
    BillService billService;

    @Autowired
    BillContentService billContentService;

    private static final Logger log = LoggerFactory.getLogger(DataNetService.class);

    private static void initJSONHeader(final HttpServletResponse httpResponse){
        httpResponse.setHeader("Connection", "close");
        httpResponse.setHeader("Content-Type", "application/json");
        httpResponse.setHeader("Expires", "Thu, 19 Nov 1981 08:52:00 GMT");
        httpResponse.setHeader("Cache-Control", "no-store, no-cache, must-revalidate, post-check=0, pre-check=0");
        httpResponse.setHeader("Pragma", "no-cache");
        httpResponse.setCharacterEncoding("UTF-8");
    }

    @RequestMapping(value = "/getAllFamily")
    public void getAllFamily(final HttpServletRequest httpRequest, final HttpServletResponse httpResponse) {
        try {
            initJSONHeader(httpResponse);
            PrintWriter out = httpResponse.getWriter();
            List<Family> families = familyService.getAll();
            out.print("[");
            for (Iterator<Family> itFamily = families.iterator(); itFamily.hasNext();) {
                Family family = itFamily.next();
                family.printJSON(out);
                if (itFamily.hasNext()) out.print(",");
            }
            out.print("]");
            out.flush();
            out.close();
        } catch (IOException ex) {
            log.error("getAllFamily {}", ex);
        }
    }

    @RequestMapping(value = "/saveFamily")
    public void saveFamily(final HttpServletRequest httpRequest, final HttpServletResponse httpResponse) {
        try {

            String data = httpRequest.getParameter("data");
            String familyId = "";
            if (data != null && data.length() > 0){
                try {
                    JSONParser parser = new JSONParser();
                    JSONObject jObj = (JSONObject)parser.parse(data);
                    Family family;
                    Object obj = jObj.get("id");
                    if (obj != null) {
                        int id = ((Long)obj).intValue();
                        family = this.familyService.getById(id);
                    } else {
                        family = new Family();
                    }
                    family.setWithJSONObject(jObj);
                    this.familyService.save(family);

                    familyId = family.getId().toString();

                } catch (ParseException e) {
                    log.error("try to parse json" + e);
                }
            }

            initJSONHeader(httpResponse);
            PrintWriter out = httpResponse.getWriter();
            out.print(familyId);
            out.flush();
            out.close();
        } catch (IOException ex) {
            log.error("saveFamily {}", ex);
        }
    }

    @RequestMapping(value = "/getFamilyMembers")
    public void getFamilyMembers(final HttpServletRequest httpRequest, final HttpServletResponse httpResponse) {
        try {
            initJSONHeader(httpResponse);
            PrintWriter out = httpResponse.getWriter();
            String data = httpRequest.getParameter("data");
            Integer familyId = Integer.parseInt(data);
            List<FamilyMember> familyMembers = familyMemberService.getAllForFamily(familyId);
            out.print("[");
            for (Iterator<FamilyMember> itFamilyMember = familyMembers.iterator(); itFamilyMember.hasNext();) {
                FamilyMember familyMember = itFamilyMember.next();
                familyMember.printJSON(out);
                if (itFamilyMember.hasNext()) out.print(",");
            }
            out.print("]");
            out.flush();
            out.close();
        } catch (IOException ex) {
            log.error("getFamilyMembers {}", ex);
        }
    }


    @RequestMapping(value = "/saveFamilyMembers")
    public void saveFamilyMembers(final HttpServletRequest httpRequest, final HttpServletResponse httpResponse) {
        try {
            String data = httpRequest.getParameter("data");
            if (data != null && data.length() > 0){
                try {
                    JSONParser parser = new JSONParser();
                    JSONArray jData = (JSONArray)parser.parse(data);

                    int n = jData.size();
                    for(int i = 0; i < n; i++) {
                        JSONObject jObj = (JSONObject)jData.get(i);
                        FamilyMember familyMember;
                        Object obj = jObj.get("id");
                        if (obj != null) {
                            int id = ((Long)obj).intValue();
                            familyMember = this.familyMemberService.getById(id);
                        } else {
                            familyMember = new FamilyMember();
                        }
                        familyMember.setWithJSONObject(jObj);
                        this.familyMemberService.save(familyMember);
                    }
                } catch (ParseException e) {
                    log.error("try to parse json" + e);
                }
            }

            initJSONHeader(httpResponse);
            PrintWriter out = httpResponse.getWriter();
            out.print("ok");
            out.flush();
            out.close();
        } catch (IOException ex) {
            log.error("saveFamilyMembers {}", ex);
        }
    }

    @RequestMapping(value = "/getGoods")
    public void getGoods(final HttpServletRequest httpRequest, final HttpServletResponse httpResponse) {
        try {
            initJSONHeader(httpResponse);
            PrintWriter out = httpResponse.getWriter();
            String data = httpRequest.getParameter("data");
            Integer index = 0;
            if (data != null && data.length() > 0) {
                index = Integer.parseInt(data);
            }

            List<Goods> goodsList = goodsService.getAll();
            out.print("[");
            for (Iterator<Goods> itGoods = goodsList.iterator(); itGoods.hasNext();) {
                Goods goods = itGoods.next();
                goods.printJSON(out);
                if (itGoods.hasNext()) out.print(",");
            }
            out.print("]");
            out.flush();
            out.close();
        } catch (IOException ex) {
            log.error("getGoods {}", ex);
        }
    }

    @RequestMapping(value = "/saveGoods")
    public void saveGoods(final HttpServletRequest httpRequest, final HttpServletResponse httpResponse) {
        try {

            String data = httpRequest.getParameter("data");
            if (data != null && data.length() > 0) {
                try {
                    JSONParser parser = new JSONParser();
                    JSONObject jObj = (JSONObject)parser.parse(data);
                    Goods goods;
                    Object obj = jObj.get("id");
                    if (obj != null) {
                        int id = ((Long)obj).intValue();
                        goods = this.goodsService.getById(id);
                    } else {
                        goods = new Goods();
                    }
                    goods.setWithJSONObject(jObj);
                    this.goodsService.save(goods);

                } catch (ParseException e) {
                    log.error("try to parse json" + e);
                }
            }

            initJSONHeader(httpResponse);
            PrintWriter out = httpResponse.getWriter();
            out.print("ok");
            out.flush();
            out.close();
        } catch (IOException ex) {
            log.error("saveGoods {}", ex);
        }
    }

    @RequestMapping(value = "/getBills")
    public void getBills(final HttpServletRequest httpRequest, final HttpServletResponse httpResponse) {
        try {
            initJSONHeader(httpResponse);
            PrintWriter out = httpResponse.getWriter();
            String data = httpRequest.getParameter("data");
            Integer index = 0;
            if (data != null && data.length() > 0) {
                index = Integer.parseInt(data);
            }

            List<Bill> billList = billService.getAll();
            out.print("[");
            for (Iterator<Bill> itBill = billList.iterator(); itBill.hasNext();) {
                Bill bill = itBill.next();
                out.print(bill.getJSON().toJSONString());
                if (itBill.hasNext()) out.print(",");
            }
            out.print("]");
            out.flush();
            out.close();
        } catch (IOException ex) {
            log.error("getBills {}", ex);
        }
    }

    @RequestMapping(value = "/getBillContents")
    public void getBillContents(final HttpServletRequest httpRequest, final HttpServletResponse httpResponse) {
        try {
            initJSONHeader(httpResponse);
            PrintWriter out = httpResponse.getWriter();

            List<BillContent> billContentList = billContentService.getAll();
            out.print("[");
            for (Iterator<BillContent> itBill = billContentList.iterator(); itBill.hasNext();) {
                BillContent bill = itBill.next();
                out.print(bill.getJSON().toJSONString());
                if (itBill.hasNext()) out.print(",");
            }
            out.print("]");
            out.flush();
            out.close();
        } catch (IOException ex) {
            log.error("getBillContents {}", ex);
        }
    }

}
